package com.xiguaji.tiktok.task.aweme.spider;

import com.xiguaji.boot.retry.RetryableException;
import com.xiguaji.tiktok.task.aweme.spider.model.AwemeResponse;
import com.xiguaji.tiktok.task.aweme.spider.model.BloggerAwemesResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class AwemeClient {
    @Autowired
    RestTemplate restTemplate;

    @Value("${xiguaji.spider.host}")
    String host;

    @Retryable(value = RetryableException.class, maxAttempts = 5)
    public AwemeResponse get() {
        String uri = host + "/aweme/FeedV1?region=US";
        ResponseEntity<AwemeResponse> responseEntity = restTemplate.getForEntity(uri, AwemeResponse.class);
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new RuntimeException(String.format("get aweme error. status: %s . msg: %s", responseEntity.getStatusCodeValue(), responseEntity.getBody()));
        }
        if (responseEntity.getBody() == null) {
            throw new RetryableException("get aweme error, retry times 5. uri:" + uri);
        }
        return responseEntity.getBody();
    }

    @Retryable(value = RetryableException.class, maxAttempts = 7)
    public BloggerAwemesResponse getBloggerAwemes(long uid, long max_cursor, int count) {
        String uri = host + "/aweme/AwemePostFromUid?user_id={user_id}&max_cursor={max_cursor}&count={count}&region=US";
        ResponseEntity<BloggerAwemesResponse> responseEntity = restTemplate.getForEntity(uri, BloggerAwemesResponse.class, uid, max_cursor, count);
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new RuntimeException(String.format("get blogger awemes error. status: %s . msg: %s", responseEntity.getStatusCodeValue(), responseEntity.getBody()));
        }
        if (responseEntity.getBody() == null) {
            throw new RetryableException("get blogger awemes error, retry times 7. uri:" + uri + " max_cursor:" + max_cursor + " count:" + count);
        }
        return responseEntity.getBody();
    }
}
